package hejie.admin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import publics.model.Admin;
import publics.util.Page;

import hejie.admin.dao.AdminDao;
import hejie.admin.service.AdminService;

@Component("adminService")
public class AdminServiceImp implements AdminService{


	AdminDao adminDao;
	
	public AdminDao getAdminDao() {
		return adminDao;
	}	
	@Resource(name="adminDao")
	public void setAdminDao(AdminDao adminDao) {
		this.adminDao = adminDao;
		System.out.println("adminDaoImpl inject in AdminServiceImpl");
	}

	public Object saveAdmin(Admin admin) {
		List<Admin> adminUsers = adminDao.findByUser(admin.getUser());	
		if(adminUsers.size() == 0){
			return adminDao.save(admin);		
		}
		else 			
		   return null;
	}

	public Page findByPage(Page page) {
		StringBuffer sql = new StringBuffer();
		sql.append("from Admin a");
		if(page.getConditions().size() > 0){//这里为模糊查询的 sql 语句拼接 请仔细体会
			sql.append(" where ");  
			for(int i = 0; i < page.getConditions().size(); ){
				sql.append("( a.name like '%").append(page.getConditions().get(i)).append("%'")//查询条件一  公司名字字段
				.append(" or a.user like '%").append(page.getConditions().get(i)).append("%'")
				.append(" or a.sex like '%").append(page.getConditions().get(i)).append("%'")
				.append(" or a.post like '%").append(page.getConditions().get(i)).append("%'")
				.append(" or a.phone like '%").append(page.getConditions().get(i)).append("%'")
				.append(" or a.right in ( select id from Right r where r.name like '%").append(page.getConditions().get(i)).append("%' ) ")
				.append(" or a.email like '%").append(page.getConditions().get(i)).append("%' ) ");
				//上面这句是在企业类型表里找符合条件的权限类型，因为权限类型是外键，所以要这么做。
				//每次上面七个属性只有匹配到的才能取到值，不然为%
				i++;
				if(i < page.getConditions().size()){// 如果条件不止一个 进行连续拼接
					sql.append(" and ");
				}
			}
		}
		System.out.println("sql ="+sql);
		int pageSize = page.getLimit();
		int offset = page.getStart();//-1)*pageSize;
		System.out.println("offset");
		page.setRoot(adminDao.findByPage(sql.toString(),offset,pageSize));//把查询结果放入root中
		System.out.println("setRoot");
		page.setTotalProperty(adminDao.findByCount(sql.toString()));   //把数据总数放入totalProperty中	
		System.out.println("setTotalProperty");
		return page;
	}

	public boolean updateAdmin(Admin admin) {
		return adminDao.update(admin);

	}

	public boolean deleteAdmin(Integer id) {
		System.out.println("service里 adminId="+id);
		return adminDao.deleteById(id);
	} 	
}
